<template>
  <view ref="containerRef" class="chat-input-container" >
    <up-card margin="0px" padding="0px">
      <template #body>
        <up-row gutter="10" custom-style="padding: 5px 5px 5px 5px">
          <up-col span="9">
            <up-textarea
              v-model="val"
              class="input"
              height="20"
              maxlength="500"
              auto-height
              confirm-type="发送"
              :show-confirm-bar="false"
              :selection-start="val.length"
              :cursor-spacing="60"
              @focus="onInputFocus"
              @blur="onInputBlur"
              @confirm="onSend"
            ></up-textarea>
          </up-col>
          <up-col span="3">
            <up-button
              style="height: 38px;"
              type="primary"
              text="发送"
              :hairline="false"
              @click="onSendText"
            ></up-button>
          </up-col>
        </up-row>
        <up-row gutter="10" custom-style="margin-bottom: 15px; padding: 5px 0 0 5px">
          <up-col span="2">
            <up-icon size="25" name="mic" @click="openRecording"></up-icon>
          </up-col>
          <!--  #ifdef  H5 -->
          <up-col span="2">
            <up-icon size="25" name="photo" @click="openPhotoAlbumH5"></up-icon>
          </up-col>
          <up-col span="2">
            <up-icon size="25" name="photo-fill" @click="openVideoAlbumH5"></up-icon>
          </up-col>
          <!--  #endif -->
          <!--  #ifdef  MP-WEIXIN || MP-TOUTIAO || MP-XHS || APP-PLUS -->
          <up-col span="2">
            <up-icon size="25" name="photo" @click="selectMediaFile"></up-icon>
          </up-col>
          <up-col span="2">
            <up-icon size="25" name="camera" @click="shootMediaFile"></up-icon>
          </up-col>
          <!--  #endif -->

          <up-col span="2">
            <up-icon size="25" name="scan" @click="openRecording"></up-icon>
          </up-col>
          <up-col span="2">
            <up-icon size="25" name="gift" @click="openRecording"></up-icon>
          </up-col>
          <up-col span="2">
            <up-icon size="25" name="plus-circle" @click="openRecording"></up-icon>
          </up-col>
        </up-row>
        <view v-if="functionBodyFlag" >
        </view>
      </template>
    </up-card>
  </view>
</template>

<script setup lang="ts">
import { guid } from 'uview-plus';
import { to } from 'await-to-js';

import { ChatMessageVo } from '@/types/IMMessageDTO';
import useUserStore from '@/store/modules/user';
import { captureCover } from '@/utils';

const userStore = useUserStore();

const emits = defineEmits(['sendCallBack', 'setListHeight']);


const val = ref('');
const containerRef = ref(null);
const functionBodyFlag = ref(false);


const onSendText = async () => {
  const message = val.value.trim();
  if (!message) return;
  const data = {
    id: guid(),
    type: 'TEXT',
    content: message,
    sendUserId: userStore.userId,
    sendTime: new Date(),
    sendUserName: userStore.nickName,
    sendUserAvatar: userStore.avatar,
    uploadFlag: false
  };
  emits('sendCallBack', { ...data });
  data.id = null;
  const [err, res] = await to(uni.$u.http.post(`/work/chatGroup/addChatTextMessage`, data));
  if (res) {
    val.value = '';
    setHeight();
  }

};

const clearInput = () => {
  val.value = '';
};
//输入框鼠标聚焦
const onInputFocus = (e) => {

  // #ifdef H5
  setHeight();
  // #endif
};
//输入框鼠标失焦
const onInputBlur = () => {

};

//打开录音
const openRecording = async () => {
  uni.hideKeyboard();
  emits('setListHeight', '41.6vh', true);
  functionBodyFlag.value = true;
};


//h5端选择图片
const openPhotoAlbumH5 = async () => {
  const res = await uni.chooseImage({
    count: 6,
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'] //从相册选择
  });
  res.tempFilePaths.forEach((url) => {
    const data: ChatMessageVo = {
      id: guid(),
      type: 'IMAGE',
      sendUserId: userStore.userId,
      sendTime: new Date(),
      sendUserName: userStore.nickName,
      sendUserAvatar: userStore.avatar,
      content: url,
      uploadFlag: false
    };
    emits('sendCallBack', data);
    uploadFile(data);

  });

};
//h5端选择视频
const openVideoAlbumH5 = async () => {
  const res = await uni.chooseVideo({
    count: 6,
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'] //从相册选择
  });
  const videoCover = await captureCover(res.tempFilePath);
  const data: ChatMessageVo = {
    id: guid(),
    type: 'VIDEO',
    sendUserId: userStore.userId,
    sendTime: new Date(),
    sendUserName: userStore.nickName,
    sendUserAvatar: userStore.avatar,
    content: res.tempFilePath,
    videoCover: videoCover,
    uploadFlag: false
  };
  emits('sendCallBack', data);
  uploadFile(data);
};
//小程序端选择媒体文件
const selectMediaFile = async () => {
  uni.chooseMedia({
    count: 9,
    mediaType: ['image', 'video'],
    sourceType: ['album'],
    success: function(res) {
      res.tempFiles.forEach(async (file) => {
        const videoCover = await captureCover(file.tempFilePath);
        const data: ChatMessageVo = {
          id: guid(),
          type: file.fileType == 'image' ? 'IMAGE' : 'VIDEO',
          sendUserId: userStore.userId,
          sendTime: new Date(),
          sendUserName: userStore.nickName,
          sendUserAvatar: userStore.avatar,
          content: file.tempFilePath,
          videoCover: videoCover,
          uploadFlag: false
        };
        emits('sendCallBack', data);
        uploadFile(data);

      });

    }
  });
};
//小程序端拍摄1、媒体文件
const shootMediaFile = () => {
  uni.chooseMedia({
    count: 1,
    maxDuration: 30,
    mediaType: ['image', 'video'],
    sourceType: ['camera'],
    camera: 'back',
    success: function(res) {
      console.log(res);
    }
  });
};


const uploadImgUrl = ref('/work/chatGroup/addChatMediaMessage'); // 上传的媒体文件服务器地址
const uploadFile = (data: ChatMessageVo) => {
  uni?.$u?.http?.upload(
    uploadImgUrl.value,
    {
      formData: {
        mediaType: data.type,
        mediaId: data.id,
        videoCover: data.videoCover
      },
      filePath: data.content,
      name: 'file'
    }
  );
};

//初始化时- 设置聊天列表高度
const setHeight = () => {
  functionBodyFlag.value = false;
  // #ifdef H5
  if (containerRef.value?.$el) {
    const keyboardHeight = containerRef.value.$el.offsetHeight;
    const height = uni.getSystemInfoSync().windowHeight - keyboardHeight + 'px';
    emits('setListHeight', height, true);
    return;
  }
  // #endif
  // #ifndef H5
  emits('setListHeight', '87.3vh', true);
  //#endif
};
//关闭功能面板
const closeFunctionBody = () => {
  functionBodyFlag.value = false;
};

onLoad(() => {
  //#ifdef APP-PLUS || MP-WEIXIN
  // 监听键盘高度变化
  uni.onKeyboardHeightChange(res => {
    if (res.height > 0) {
      const height = functionBodyFlag.value == true ? '42vh' : '87.3vh';
      functionBodyFlag.value = false;
      emits('setListHeight', height, true);
    } else {
      // emits('setListHeight',  '87.3vh', true);
    }
  });
  //#endif
});
onUnload(() => {
  //#ifdef APP-PLUS || MP-WEIXIN
  // 页面卸载时取消监听
  uni.offKeyboardHeightChange();
  //#endif
});

defineExpose({
  setHeight,
  clearInput,
  closeFunctionBody
});
</script>

<style scoped lang="scss">
.chat-input-container {
  width: 100%;
  box-sizing: border-box;
}

.input {
  max-height: 4.5em;
  line-height: 1em;
  overflow-y: auto;
}
</style>
